package cn.wtg.kotlinlib.utils

import androidx.annotation.AnimRes
import androidx.annotation.AnimatorRes
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import cn.wtg.kotlinlib.R

/**
 * author: wtg
 * time: 2022/11/14
 * desc:
 */
object FragmentHelper {
    /**
     * 切换fragment
     *
     * @param manager manager
     * @param to 跳转的fragment
     * @param tag tag
     * @param fgmId 容器布局id
     * @param isAddBackStack 是否加入返回栈 true是 false否
     */
    @JvmOverloads
    fun replaceFragment(
        manager: FragmentManager?,
        to: Fragment?,
        tag: String?,
        fgmId: Int,
        isAddBackStack: Boolean,
        @AnimatorRes @AnimRes enter: Int = R.anim.anim_slide_in_right,
        @AnimatorRes @AnimRes exit: Int = 0,
        @AnimatorRes @AnimRes popEnter: Int = 0,
        @AnimatorRes @AnimRes popExit: Int = R.anim.anim_slide_out_right
    ) {
        if (manager == null || to == null) {
            return
        }
        val transaction = manager.beginTransaction()
        transaction.setCustomAnimations(
            R.anim.anim_slide_in_right,
            0,
            0,
            R.anim.anim_slide_out_right
        )
        if (isAddBackStack) {
            transaction.addToBackStack(tag)
        }
        transaction.replace(fgmId, to, tag)
        transaction.commit()
    }

    /**
     * 添加到回退栈
     *
     * @param manager manager
     * @param to 跳转的fragment
     * @param tag tag
     * @param fgmId 容器布局id
     */
    fun replaceBackStackFragment(
        manager: FragmentManager?,
        to: Fragment?,
        tag: String?,
        fgmId: Int
    ) {
        replaceFragment(manager, to, tag, fgmId, true)
    }

    /**
     * 不添加到回退栈
     *
     * @param manager manager
     * @param to 跳转的fragment
     * @param tag tag
     * @param fgmId 容器布局id
     */
    fun replaceNoBackStackFragment(
        manager: FragmentManager?,
        to: Fragment?,
        tag: String?,
        fgmId: Int
    ) {
        replaceFragment(manager, to, tag, fgmId, false)
    }
}